/**
 * 
 */
package org.seckill.service.impl;

import java.util.List;

import org.seckill.dao.SysAreaDao;
import org.seckill.entry.SysArea;
import org.seckill.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * 
 * @author yue
 * 2016年8月7日 下午6:44:45
 */
@Service
public class SysAreaServiceImpl implements  SysAreaService{

	@Autowired
	private SysAreaDao sysAreaDao;
	/* 
	 * @return 
	 */
	@Override
	public String getTreeJsonDate(String code) throws Exception {
		String res = null;
		if(code != null){
			String cc = HandlerCode(code);
			List<SysArea> sysAreaList = sysAreaDao.getTreeJsonDate(cc);
			res = handlerJson(sysAreaList,code);
		}else{	//根节点
			res = handlerJson();
		}
		return res;
	}
	
	/**
	 * @return
	 */
	private String handlerJson() {
		JsonArray array = new JsonArray();
		JsonObject obj = new JsonObject();
		obj.addProperty("id", "0");
		obj.addProperty("text", "全国");
		obj.addProperty("state", "closed");
		obj.addProperty("iconCls", "icon-man");
		array.add(obj);
		return array.toString();
	}

	/**
	 * 生成tree列表json
	 * @param sysAreaList
	 * @param code 
	 * @return
	 */
	private String handlerJson(List<SysArea> sysAreaList, String code) {
		/*
		 * [{"id":1,"text":"Java","children":[{"id":11,"text":"ME","state":"closed"}] }]
		 */
		if(sysAreaList == null || sysAreaList.isEmpty()){
			return null;
		}
		JsonArray array = new JsonArray();
		for(SysArea a:sysAreaList){
			JsonObject obj = new JsonObject();
			if(code != null && code.equals(a.getAreaCode())){ //去掉自己
				continue;
			}
			obj.addProperty("id", a.getAreaCode());
			obj.addProperty("text", a.getAreaName());
			//obj.addProperty("attributes",);
			obj.addProperty("state", a.getAreaLevel() == 3?"open":"closed");
			obj.addProperty("iconCls", "icon-man");
			array.add(obj);
		}
		return array.toString();
	}
	
	/**
	 * code处理
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	private String HandlerCode(String code) throws Exception{
		if("0".equals(code)){//查找省级 %0000
			return "%0000";
		}else if(code.endsWith("0000")){//查找市级 420%00
			return code.substring(0, 3)+"%00";
		}else if(code.endsWith("00")){//查找区县级	4201%
			return code.substring(0, 4)+"%";
		}else{
			throw new Exception("参数异常");
		}
	}


}
